<template>
	<div class="edit-dealer">
		<el-dialog
			class="edit-drawer edit-dealer-drawder"
			:title="
				!isCreate
					? $t('system.staff_manage.edit_account')
					: $t('system.staff_manage.add_account')
			"
			:visible="drawer"
			:before-close="handleClose"
			:close-on-click-modal="false"
			:width="getWidth('810px')"
			:destroy-on-close="true"
			@close="handleClose"
		>
			<el-form
				ref="form"
				:inline="true"
				:model="form"
				:rules="rules"
				label-width="120px"
			>
				<el-form-item :label="`${$t('system.name')}:`" prop="userName">
					<el-input
						v-model="form.userName"
						v-symbols
						:disabled="!isCreate"
						maxlength="10"
						style="width:202px;"
						:placeholder="$t('common.please_enter')"
						@input="
							form.userName = form.userName.replace(
								/[\u4e00-\u9fa5]/g,
								''
							)
						"
					></el-input>
				</el-form-item>

				<el-form-item :label="`${$t('common.name')}:`" prop="nickName">
					<el-input
						v-model="form.nickName"
						v-symbols
						maxlength="10"
						style="width:202px;"
						:placeholder="$t('common.please_enter')"
					></el-input>
				</el-form-item>

				<template v-if="isCreate">
					<PasswordWithEye
						:label="`${$t('system.staff_manage.login_password')}:`"
						prop="pwd"
						:form="form"
						:placeholder="$t('common.please_enter')"
						@handleInput="form.pwd = $event"
					></PasswordWithEye>

					<PasswordWithEye
						:label="
							`${$t(
								'system.staff_manage.confirm_login_password'
							)}:`
						"
						prop="rePwd"
						:form="form"
						:placeholder="$t('common.please_enter')"
						@handleInput="form.rePwd = $event"
					></PasswordWithEye>
				</template>
				<el-form-item
					:label="`${$t('common.choose_merchant')}:`"
					prop="merchantId"
				>
					<el-select
						v-model="form.merchantId"
						size="medium"
						filterable
						@change="handleMerchantChange"
					>
						<el-option
							v-if="isZk"
							:label="`${$t('system.all')}`"
							value="0"
						></el-option>
						<el-option
							v-for="item in merchantList"
							:key="item.id"
							:label="item.merchantName"
							:value="item.id"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item
					:label="`${$t('common.number_type')}:`"
					prop="userType"
				>
					<el-select
						v-model="form.userType"
						:placeholder="$t('common.please_choose')"
					>
						<el-option
							v-for="item in userTypeList"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>
				<el-row>
					<el-form-item
						:label="`${$t('system.staff_manage.secret')}:`"
						prop="googleAuthCode"
					>
						<el-input
							v-model="form.googleAuthCode"
							v-symbols
							disabled
							style="width:202px;"
							:placeholder="$t('system.staff_manage.input')"
						></el-input>
					</el-form-item>
					<el-form-item v-if="isCreate">
						<el-button type="primary" size="mini" @click="copyCode">
							复制
						</el-button>
					</el-form-item>
				</el-row>
				<el-form-item
					v-if="!isCreate"
					:label="`${$t('system.staff_manage.leave')}:`"
					prop="active"
				>
					<el-radio-group v-model="form.active">
						<el-radio
							v-for="item in userActiveType"
							:key="item.code"
							:label="item.code * 1"
						>
							{{ item.description }}
						</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item
					:label="`${$t('system.staff_manage.assgin_role')}:`"
					prop="tranferVal"
					class="required"
				>
					<el-transfer
						ref="transfer"
						v-model="form.tranferVal"
						class="transfer"
						:titles="[
							$t('system.staff_manage.select_role'),
							$t('system.staff_manage.selected_role')
						]"
						:data="permissionList"
						:props="{ key: 'id', label: 'roleName' }"
					></el-transfer>
				</el-form-item>
			</el-form>
			<div slot="footer" style="text-align: center">
				<el-button
					type="default"
					class="item"
					@click.native="handleClose"
				>
					{{ $t('common.cancel') }}
				</el-button>
				<el-button
					type="primary"
					class="item"
					:loading="confirmLoading"
					@click.native="handleSure"
				>
					{{ $t('common.confirm') }}
				</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import { editUser, addUser } from '@/api/user'
import { message } from '@/utils/message'
import PasswordWithEye from '@/components/PasswordWithEye'
import validate from '@/mixins/validate'
import list from '@/mixins/list'
import { testSpecial } from '@/utils/test'
import md5 from 'js-md5'

export default {
	name: 'EditAccout',
	components: {
		PasswordWithEye
	},
	mixins: [list, validate],
	props: {
		isCreate: Boolean,
		drawer: Boolean,
		editData: {
			type: Object,
			default: function() {
				return {}
			}
		}
	},
	data() {
		return {
			permissionList: [],
			checkedKeys: [],
			showPassword: true,
			time: '',
			loading: false,
			roleOptions: [],
			form: {
				active: 1,
				userName: '',
				nickName: '',
				pwd: '',
				rePwd: '',
				roleIds: [],
				googleAuthCode: '',
				merchantId: '',
				userType: '',
				merchantCode: '',
				tranferVal: []
			},
			innerVisible: false,
			dialogTableVisible: false,
			multipleSelection: [],
			previewUrl: '',
			currentMerchantInfo: {},
			userTypeList: [],
			confirmLoading: false
		}
	},
	computed: {
		isZk() {
			return this.$store.getters.isZk
		},
		merchantList() {
			return this.$store.getters.merchantList || []
		},
		currentUserType() {
			return this.$store.getters.userInfo.userType
		},
		currentMerchantId() {
			return this.$store.getters.merchantInfo.id || '0'
		},
		userActiveType() {
			return this.globalDics.userActive || []
		},
		rules() {
			const validateAuth = (rule, value, callback) => {
				const err = new Error(this.$t('system.staff_manage.input'))
				if (!value) {
					callback(err)
				} else {
					this.$refs.form.validateField('rePwd')
					callback()
				}
			}
			const validateUserName = (rule, value, callback) => {
				if (!value) {
					callback(
						this.$t('system.staff_manage.use_name_is_not_empty')
					)
				} else if (!testSpecial(value)) {
					callback(this.$t('system.staff_manage.not'))
				} else {
					callback()
				}
			}
			const validateNickName = (rule, value, callback) => {
				if (!value) {
					callback(this.$t('system.staff_manage.name_is_not_empty'))
				} else if (!testSpecial(value)) {
					callback(this.$t('system.staff_manage.not'))
				} else {
					callback()
				}
			}
			return {
				pwd: [
					{
						required: true,
						validator: this.validatePass,
						trigger: 'blur'
					}
				],
				rePwd: [
					{
						required: true,
						validator: this.validateRePass,
						trigger: 'blur'
					}
				],
				merchantId: [
					{
						required: true,
						message: this.$t('common.please_choose'),
						trigger: 'change'
					}
				],
				userType: [
					{
						required: true,
						message: this.$t('common.please_choose'),
						trigger: 'change'
					}
				],
				active: [
					{
						required: true,
						message: this.$t('common.please_choose'),
						trigger: 'change'
					}
				],
				userName: [
					{
						required: true,
						trigger: ['blur', 'change'],
						validator: validateUserName
					},
					{
						min: 2,
						max: 10,
						message: this.$t('system.staff_manage.limit'),
						trigger: 'blur'
					}
				],
				nickName: [
					{
						required: true,
						trigger: ['blur', 'change'],
						validator: validateNickName
					},
					{
						min: 2,
						max: 10,
						message: this.$t('system.staff_manage.limit'),
						trigger: 'blur'
					}
				],
				googleAuthCode: [
					{
						required: true,
						trigger: 'blur',
						message: this.$t('system.staff_manage.input'),
						validateAuth
					}
				],
				tranferVal: [
					{
						required: true,
						trigger: 'blur',
						message: this.$t('system.staff_manage.assigning_roles')
					}
				]
			}
		}
	},
	mounted() {
		this.listLoading = true
		if (this.isCreate) {
			this.form.merchantId = this.currentMerchantId
			this.queryRoleList()
			this.getGoogleAuth()
			this.queryUserTypeList()
		} else {
			this.form.id = this.editData.id
			this.form.userName = this.editData.userName
			this.form.nickName = this.editData.nickName
			this.form.active = this.editData.active
			this.form.googleAuthCode = this.editData.googleAuthCode
			this.form.merchantId = this.editData.merchantId + ''
			// this.form.userType = this.editData.userType + ''
			this.form.merchantCode = this.editData.merchantCode
			this.queryUserRles()
			this.queryUserTypeList(true)
		}
	},
	methods: {
		copyCode() {
			this.$message.closeAll()
			this.$copyText(this.form.googleAuthCode).then(() => {
				this.$message.success(this.$t('common.copy'))
			})
		},
		queryUserRles() {
			this.$api
				.getUserRoles({
					id: this.editData.id,
					merchantId: this.editData.merchantId
				})
				.then((res) => {
					const allowUserRole = res.data?.allowUserRole

					this.permissionList = allowUserRole
					this.form.tranferVal = allowUserRole
						.filter((element) => {
							return element.isExist === '1'
						})
						.map((item) => item.id)
				})
		},
		handleMerchantChange() {
			this.queryRoleList()
			this.queryUserTypeList()
			this.form.tranferVal = [] // 每次选择完商户，上次的已选择角色清空
			this.currentMerchantInfo = this.merchantList.find(
				(item) => item.id === this.form.merchantId
			)
		},

		queryRoleList() {
			this.$api
				.getRoleList({
					merchantId: this.form.merchantId,
					pageNum: 1,
					pageSize: 9999
				})
				.then((res) => {
					this.listLoading = false
					this.permissionList = res.data?.record || []
					if (!res.data?.record) {
						this.$parent.notHasRoles = true
					}
				})
		},
		async queryUserTypeList(isEditMounted = false) {
			this.form.userType = ''
			this.userTypeList = []
			await this.$api
				.queryUserTypeListApi({
					userType: this.currentUserType,
					merchantId: this.form.merchantId
				})
				.then((res) => {
					if (res?.code === 200) {
						this.userTypeList = res?.data
						// 编辑首次加载
						if (isEditMounted) {
							this.form.userType = this.editData.userType + ''
						}
					}
				})
		},
		getGoogleAuth() {
			this.$api.googleAuth().then((res) => {
				if (res?.code === 200) {
					this.form.googleAuthCode = res.data
				}
			})
		},
		handleChoose() {
			this.dialogTableVisible = true
			this.$refs['form'].resetFields()
		},
		handleSure() {
			if (this.timeout) clearTimeout(this.timeout)

			this.timeout = setTimeout(() => {
				this.$refs['form'].validate((valid) => {
					if (valid) {
						if (this.form.tranferVal.length === 0) {
							message({
								message: this.$t(
									'system.staff_manage.please_select_role'
								),
								type: 'error'
							})
							return
						}
						const handle = this.isCreate ? addUser : editUser
						const params = this.isCreate
							? {
									...this.form,
									roleIds: this.form.tranferVal,
									googleAuthCode: this.form.googleAuthCode,
									pwd: md5(
										this.form.userName.trim() +
											this.form.pwd.trim()
									),
									rePwd: md5(
										this.form.userName.trim() +
											this.form.rePwd.trim()
									)
							  }
							: {
									nickName: this.form.nickName,
									id: this.form.id,
									userName: this.form.userName,
									roleIds: this.form.tranferVal,
									googleAuthCode: this.form.googleAuthCode,
									active: this.form.active,
									merchantId: this.form.merchantId,
									userType: this.form.userType,
									merchantCode: this.currentMerchantInfo
										?.merchantCode
							  }
						this.confirmLoading = true
						handle(params)
							.then((res) => {
								if (res.code === 200) {
									this.$emit('update:drawer', false)
									message({
										message: this.$t(
											'common.action_success'
										),
										type: 'success'
									})
									this.$parent.loadData()
								}
							})
							.catch(() => {})
							.finally(() => {
								this.confirmLoading = false
							})
					} else {
						return false
					}
				})
			}, 300)
		},
		handleClose() {
			this.$emit('update:drawer', false)
			this.form.tranferVal = []
			this.$refs['form'].resetFields()
			this.permissionList = []
		},
		handleSelectionChange(val) {
			this.multipleSelection = val
		},
		handleCheck(row) {
			this.innerVisible = true
		}
	}
}
</script>

<style lang="scss" scoped>
::v-deep .el-checkbox {
	width: 80%;
}
.required {
	::v-deep .el-form-item__label:before {
		content: '*';
		color: #ff4949;
		margin-right: 4px;
	}
}

.edit-drawer {
	.card {
		margin: 0 15px;
	}
	.item {
		margin-right: 30px;
	}

	.round {
		padding: 0 50px;
	}

	.handles {
		padding-left: 50px;
		margin-top: 30px;
		text-align: center;
		.item {
			margin-bottom: 15px;
		}
	}

	.transfer {
		margin-left: 56px;
	}
}
@media (max-width: 800px) {
	.edit-exp-drawer {
		.round {
			padding: 0;
		}
	}
}
::v-deep .el-dialog__header {
	border-bottom: 1px solid #00000015;
}
::v-deep .el-dialog__body {
	padding-bottom: 0;
}
::v-deep .el-transfer__buttons {
	padding: 0 45px;
}

.vi_VN,
.en_US,
.th_TH {
	.edit-drawer {
		::v-deep .el-transfer-panel {
			width: 260px;
		}
	}
}
</style>
